<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 消息管理
 * Class Consumer
 * @author heyu
 */
class Message extends MY_Controller {
	
    /**
     * @var DlnMessageModel
     */
    public $mMessage;
    
    /**
     * @var DlnUserModel
     */
    public $mMember;

	public function __construct(){
		parent::__construct();
        $this->loadModel('DlnMessageModel', 'mMessage', 'deliveryman');
        $this->loadModel('DlnUserModel', 'mMember', 'deliveryman');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		
		if ( ! adminAuthority('message-add', 'deliveryman')){
			redirect(getUrl('deliveryman/message/history'));	
		}
		
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');

	    $data = array(
	        'title' => '消息推送',
            'status' =>$this->mMember->status(),
	    	'province' => $this->mSetting->getProvinces()
        );

		$this->view('deliveryman/message/home', $data, 'datatable,validation,uniform,select2');
	}

    /**
     * 获取会员列表
     */
    public function getMemberList(){
    	
    	$name = trim(get('name'));
    	$mobile = trim(get('mobile'));
    	$status = (int)get('status');
    	$this->db->select('id,portrait,name,mobile,status')
    			 ->order_by('id desc');
    	$province = (int)get('province');
    	$county = get('county');
    	$city = (int)get('city');
    	
    	if($name){
    		$this->db->like('name', $name);
    	}
    	
    	if($mobile){
    		$this->db->where('mobile', $mobile);
    	}
    	
    	if($status){
    		$this->db->where('status', $status);
    	}
    	
    	if($province){
    		$this->db->where('province_id', $province);
    	}
    	 
    	if($city){
    		$this->db->where('city_id', $city);
    	}
    	 
    	if($county && $county[0] && is_array($county)){
    		$this->db->where_in('county_id', $county);
    	}
    	
        $data = $this->mMember->pagination($this->mMember->tbUser);
        foreach ($data['data'] as $k => $v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<input type="checkbox" class="checkboxes" name="consumer_id[]" value="' . $v['id'] .'">';
            $data['aaData'][$k][] = '<img src="'.$img.'" class="portrait img-wh"/>';
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $this->mMember->status($v['status'], true);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }
    
    /**
     * 获取用户列表
     */
    public function getList(){
    	
    	$star = trim(get('star'));
    	$end = trim(get('end'));
    	$iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
    	$sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"
    	
    	if ($star){
    		$this->db->where('a.addtime >= ', strtotime($star));
    	}
    	
    	if($end){
    		$this->db->where('a.addtime <', strtotime('+1day', strtotime($end)));
    	}
    	
    	if ($iSortCol_0 == 1){
    		$this->db->order_by('id', $sSortDir_0);
    	}else{
    		$this->db->order_by('id', 'desc');
    	}
    	
    	$table = '(select id,deliveryman_id,content,addtime,count(id) as total from '
    			.$this->mMessage->tbMessage.' where type = 1 group by addtime)a';
		 $this->db->select('a.*');   	
		$data = $this->mMessage->pagination($table);
		foreach ($data['data'] as $k => $v){
			$data['aaData'][$k][] = '<textarea readonly class="form-control remaks-item content textarea_height">'.$v['content'].'</textarea>';
			$data['aaData'][$k][] = dateFormat($v['addtime']);
			$data['aaData'][$k][] = $v['deliveryman_id'] <= 0 ? '推送所有人' : '推送'.$v['total'].'人';
			if ($v['deliveryman_id'] > 0){
				$data['aaData'][$k][] = adminCreateBtn(array(
						'label' => '明细',
						'attr' => array(
								'href' => 'javascript:;',
								'class' => 'btn btn-xs green-stripe default detail-btn',
								'time' => $v['addtime']
						),
						'tag' => 'a'
				));;
			}else{
				$data['aaData'][$k][] = '';
			}
		}
		unset($data['data']);
		echo json_encode($data);
    }

    /**
     * 保存推送
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('type', '类型', 'required|in_list[1,2]'),
            array('title', '标题', 'required'),
            array('content', '内容', 'required'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $type = (int)post('type');
        $title = post('title');
        $content = post('content');
        $data = array();
        $time = time();
        $jPushCode = array();
        
        $province = (int)post('province');
        $county = post('county');
        $city = (int)post('city');
        
        if ($type == 1){
        	if($county && $county[0]){
        		foreach ($county as $v){
        			$data[] = array(
        					'type' => 1,
        					'province_id' => $province,
        					'city_id' => $city,
        					'county_id' => $v,
        					'deliveryman_id' => 0,
        					'content' => $content,
        					'title' => $title,
        					'addtime' => $time,
        			);
        		}
        	}else{
        		$data[] = array(
        					'type' => 1,
        					'province_id' => 0,
        					'city_id' => 0,
        					'county_id' => 0,
        					'deliveryman_id' => 0,
        					'content' => $content,
                            'title' => $title,
        					'addtime' => $time,
        			);
        	}
        }else if ($type == 2) {
        	$id = post('consumer_ids');
        	//            $ids = (int)post('ids');
        	$consumerId = explode(',', trim($id, ','));
        	if (empty($consumerId)) {
        		$this->ajaxReturn(0, '请选择要推送的用户');
        	}
        	$ids = array();
        	$consumer = $this->mMember->getInfoByIds($consumerId);
        	if(count($consumer) != count($consumerId)){
        		$this->ajaxReturn(0, '参数错误');
        	}
        	foreach ($consumerId as $k => $v) {
        		$data[] = array(
        				'type' => 1,
        				'province_id' => $consumer[$v]['province_id'],
        				'city_id' => $consumer[$v]['city_id'],
        				'county_id' => $consumer[$v]['county_id'],
        				'deliveryman_id' => $v,
        				'content' => $content,
                        'title' => $title,
        				'addtime' => $time,
        		);
        	}
        	 
        	foreach ($consumer as $c){
        		$jPushCode[] = $c['jpush_code'];
        	}
        }
        
        $tA = $this->mMessage->insertBatch($this->mMessage->tbMessage, $data);
        if (!$tA){
            $this->ajaxReturn(0, '推送失败');
        }
        $type = $type == 1 ? 2 : 1;
        deliverymanJpush($title, $content, $type, $jPushCode);
        $this->ajaxReturn(1, '推送成功');
    }

    /**
     * 推送历史记录
     */
    public function history(){
        $data = array(
            'type' => $this->getType(),
            'title' => '推送历史'
        );
        $this->view('deliveryman/message/history', $data, 'datatable,datepicker');
    }

    /**
     * 获取同一时间消息推送人
     */
    public function getDetail(){
    	
    	$addTime = (int)get('addtime');
    	if (!$addTime) return false;
    	$realname = get('realname');
    	$mobile = get('mobile');
    	if ($realname){
    		$this->db->like(array('name' => $realname));
    	}
    	if ($mobile){
    		$this->db->where(array('mobile' => $mobile));
    	}
    	$this->db->select('u.portrait,u.name,u.mobile')
		    	->join($this->mMember->tbUser.' u', 'm.deliveryman_id = u.id')
		    	->where('m.addtime', $addTime)
		    	->order_by('u.id desc');
	    $data = $this->mMessage->pagination($this->mMessage->tbMessage.' m');
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '<img src="'.$v['portrait'].'" class="portrait img-wh"/>';
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 消息类型
     * @param $key
     * @return mixed|string
     */
    public function getType($key = 0){
        $config = array(
            1 => '系统消息(所有人)',
            2 => '系统消息（指定人）',
            3 => '订单消息',
        );
        if( ! $key){
            return $config;
        }
        return $config[$key];
    }
}
